<template>
  <div class="page">
    <div class="header-num">
      <div><span class="page-num">5</span><span class="page-title">申报材料上传</span></div>
      <div class="plan">5/5</div>
    </div>
    <div v-for="(item, index) in materials" :key="index" class="file-box">
      <div class="file-item">
        <div :class="`title ${item.require ? 'title-required' : ''}`">{{ item.title }}</div>
        <van-divider />
        <span v-if="item.desc" class="red-desc">{{ item.desc }}</span>
        <div class="container">
          <image-upload v-model:value="item.imgList" :fileType="item.type" :title="item.title" @uploadBack="uploadBack"></image-upload>
        </div>
      </div>
    </div>

    <div class="btn-group">
      <van-button type="button" class="cus-btn btn-default" @click="goToPrevious">上一步</van-button>
      <van-button :loading="isCommit" type="button" class="cus-btn btn-default" @click="handleSave">保存</van-button>
      <van-button :loading="isCommit" type="button" class="cus-btn btn-primary" @click="handleSubmit">提交</van-button>
    </div>
  </div>
</template>

<script>
import { reactive, onBeforeMount, toRefs, getCurrentInstance, computed } from 'vue'
import { useStore } from 'vuex'
import ImageUpload from '@/components/ImageUpload'
import { useRouter } from 'vue-router'
import { getDictData } from '@/utils/data.js'
import { Toast } from 'vant'
import { saveBuildApply } from '@/service/build-apply'
export default {
  components: {
    ImageUpload,
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const state = reactive({
      isCommit: false,
      materials: [
        { title: '农村宅基地使用承诺书', desc: '', imgList: [], require: true },
        { title: '股权证复印件', desc: '', imgList: [], require: false },
        { title: '申请人身份证复印件', desc: '', imgList: [], require: true },
        { title: '家庭成员户口本复印件', desc: '', imgList: [], require: true },
        { title: '个人建房用地界限申请表', desc: '（在红线图复印件四至签字盖章）', imgList: [], require: true },
        { title: '住宅建设用地规划红线图', desc: '（地类不明确的需勘测定界报告、勘测定界图）', imgList: [], require: true },
        { title: '无宅基地证明', desc: '（无旧宅基地的提供）', imgList: [], require: false },
        { title: '房屋设计图', desc: '', imgList: [], require: true },
        { title: '危房鉴定书', desc: '（原房屋为危房提供）', imgList: [], require: false },
        { title: '村民小组同意书', desc: '', imgList: [], require: true },
        { title: '与相邻权利人签订的书面协议或相邻权利人在房屋设计图上签字确认的材料', desc: '', imgList: [], require: true },
        { title: '村协议', desc: '（传统保护村落或有特定要求的村落提供）', imgList: [], require: false },
      ],
      fileTypeDict: [],
    })

    // 全局属性
    const { $localStorage } = getCurrentInstance().appContext.config.globalProperties
    store.dispatch('getFileServerPrefix')

    onBeforeMount(async () => {
      // 获取字段数据
      getDictData('FILE_TYPE').then((list) => {
        state.fileTypeDict = list
        list.forEach((dict) => {
          state.materials.forEach((file) => {
            if (dict.dictionaryName.includes(file.title)) {
              file.type = dict.dictionaryValue
              if (file.title === '房屋设计图') {
                file.type = 'A09'
              }
            }
          })
        })
        // 图片回显
        if ($localStorage.get('attachInfoList')) {
          let attachInfoList = JSON.parse($localStorage.get('attachInfoList'))
          attachInfoList.forEach((atta) => {
            state.materials.forEach((mater) => {
              if (atta.type === mater.type) {
                mater.imgList.push({
                  url: fileServerPrefix.value + atta.url,
                  name: atta.name,
                  size: atta.size,
                  suffix: atta.suffix,
                  type: atta.type,
                  filePath: atta.url,
                })
              }
            })
          })
        }
      })
    })
    // 上一步
    const goToPrevious = () => {
      $localStorage.set('attachInfoList', JSON.stringify(formatAllFileList()))
      router.push({ path: `/build-apply/build-info` })
    }

    // 文件上传后回调
    const uploadBack = (fileList, type) => {
      state.materials.forEach((item) => {
        if (item.type === type) {
          item.imgList = fileList
        }
      })
    }

    const formatAllFileList = () => {
      let allFileList = []
      state.materials.forEach((item) => {
        item.imgList.forEach((imgItem) => {
          allFileList.push({
            name: imgItem.name,
            size: imgItem.size,
            suffix: imgItem.suffix,
            type: imgItem.type,
            url: imgItem.filePath ? imgItem.filePath : imgItem.url,
          })
        })
      })
      allFileList.forEach((item, index) => {
        item.sort = index
      })
      return allFileList
    }

    const handSendData = (isSubmit) => {
      return new Promise((resove, reject) => {
        $localStorage.set('attachInfoList', JSON.stringify(formatAllFileList()))
        const applyUserInfo = JSON.parse($localStorage.get('applyUserInfo'))
        const familyMemberList = JSON.parse($localStorage.get('familyMemberList'))
        const homesteadForm = JSON.parse($localStorage.get('homesteadForm'))
        const buildInfo = JSON.parse($localStorage.get('buildInfo'))
        const attachInfoList = JSON.parse($localStorage.get('attachInfoList'))
        let params = Object.assign(
          { isSubmit: isSubmit, familyMemberList: familyMemberList, attachInfoList: attachInfoList },
          applyUserInfo,
          homesteadForm,
          buildInfo
        )
        state.isCommit = true
        saveBuildApply(params)
          .then((res) => {
            if (res.code == 100) {
              resove(true)
            }
            state.isCommit = false
          })
          .catch((err) => {
            state.isCommit = false
            reject(err)
          })
      })
    }

    // 保存
    const handleSave = () => {
      handSendData('0').then(() => {
        Toast.success('保存成功')
        setTimeout(() => {
          router.push({ path: '/record-apply/record-list' })
        }, 500)
      })
    }
    // 提交数据
    const handleSubmit = () => {
      for (let index = 0; index < state.materials.length; index++) {
        const mater = state.materials[index]
        if (mater.require && mater.imgList.length === 0) {
          Toast.fail(`请上传${mater.title}`)
          return
        }
      }

      handSendData('1').then(() => {
        Toast.success('提交成功')
        setTimeout(() => {
          router.push({
            name: 'ResultsPage',
            params: {
              stepList: JSON.stringify([
                { title: '建房申请提交成功', desc: '您已成功提交建房申请，请等待相关部门审批，办理时间限约35个工作日。', finishTime: '' },
                { title: '等待审批通知', desc: '审批通过后，乡镇政府下发《乡村建设规划许可证》《农村宅基地批准书》', finishTime: '' },
                { title: '领取证件，申请开工', desc: '领取到证件后，在本平台首页申请开工', finishTime: '' },
                { title: '申请竣工', desc: '住宅建成后，在本平台首页申请竣工', finishTime: '' },
              ]),
              stepActive: 1,
            },
          })
        }, 500)
      })
    }

    const fileServerPrefix = computed(() => {
      return store.state.fileServerPrefix
    })

    return {
      fileServerPrefix,
      ...toRefs(state),
      goToPrevious,
      handleSave,
      handleSubmit,
      uploadBack,
    }
  },
}
</script>

<style lang="less" scoped>
@import '@/common/style/mixin';
.file-box {
  .file-item {
    background-color: @fc;
    margin-bottom: 12px;
    .borderRadius(10px);
    .title {
      font-size: 16px;
      font-weight: bold;
      padding: 13px 14px 0;
    }
    .title-required::before {
      margin-right: 5px;
      color: var(--van-field-required-mark-color);
      content: '*';
    }
    .red-desc {
      font-size: 14px;
      font-weight: 400;
      color: #ff0000;
    }
    .container {
      padding: 8px 14px 13px;
    }
  }
}
.btn-group {
  padding: 50px 0 20px;
}
</style>
